#include "threadPool.h"
#include "train.h"
int recvn(int sockfd,void *buf,int length);
int transFile(int netfd, const char *pathname, const char *filename)
{
    train_t train;
    // 发送文件名
    train.len = (int)strlen(filename);
    memcpy(train.data, filename, train.len);
    printf("filename=%s\n", filename);
    send(netfd, &train, sizeof(int) + train.len, MSG_NOSIGNAL);
    // 打开文件
    int fd = open(pathname, O_RDWR);
    if (fd == -1)
    {
        char ret[10] = "FAIL";
        int len = 5;
        write(netfd, &len, sizeof(int));
        write(netfd, ret, len);
        return -1;
    }
    // 发送文件的总大小
    struct stat statbuf;
    fstat(fd, &statbuf);
    train.len = sizeof(statbuf.st_size);
    memcpy(train.data, &statbuf.st_size, train.len);
    send(netfd, &train, sizeof(int) + train.len, MSG_NOSIGNAL);
    // 接收客户端已下载文件的大小的信息
    recvn(netfd, &train.len, sizeof(int));
    recvn(netfd, train.data, train.len);
    off_t totalsize = 0; // 记录已经发送的长度
    memcpy(&totalsize, train.data, train.len);
    // 定位文件的读写位置
    if (totalsize > 0)
    {
        int ret = lseek(fd, totalsize, SEEK_SET);
        ERROR_CHECK(ret, -1, "lseek");
    }
    // 将总文件内容映射到内存
    char *p = (char *)mmap(NULL, statbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    ERROR_CHECK(p, MAP_FAILED, "mmap");
    while (totalsize < statbuf.st_size)
    {
        if (statbuf.st_size - totalsize > 1000)
        {
            train.len = 1000; // 剩余未发送的内容超过1000
        }
        else
        {
            train.len = statbuf.st_size - totalsize;
            // 剩余内容不足1000
        }
        send(netfd, &train.len, sizeof(train.len), MSG_NOSIGNAL); // 发火车头
        send(netfd, p + totalsize, train.len, MSG_NOSIGNAL);      // 火车车厢在mmap映射区
        totalsize += train.len;
    }
    // 补发一个空火车
    train.len = 0;
    send(netfd, &train.len, sizeof(train.len), MSG_NOSIGNAL); // 发火车头
    munmap(p, statbuf.st_size);
    close(fd);
    return 0;
}
int netDriveGets(const char *pathname, const char *filename, int netfd)
{
    char buf[1024] = {0};
    sprintf(buf, "%s/%s", pathname, filename);
    transFile(netfd, buf, filename);
    return 0;
}
